package com.guducat.collegeWeb.config;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.io.IOException;

/**
 * 安全HTTP响应头配置类
 * 添加必要的安全响应头，提高网站安全性
 */
@Configuration
public class SecurityHeadersConfig {

    /**
     * 安全响应头过滤器
     * 为所有HTTP响应添加安全相关的头部信息
     */
    @Bean
    @Order(1)
    public Filter securityHeadersFilter() {
        return new Filter() {
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                
                // X-Content-Type-Options: 防止MIME类型嗅探攻击
                httpResponse.setHeader("X-Content-Type-Options", "nosniff");
                
                // X-Frame-Options: 防止点击劫持攻击
                httpResponse.setHeader("X-Frame-Options", "DENY");
                
                // X-XSS-Protection: 启用XSS过滤器
                httpResponse.setHeader("X-XSS-Protection", "1; mode=block");
                
                // Referrer-Policy: 控制引用信息的发送
                httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
                
                // Content-Security-Policy: 内容安全策略（基础配置）
                httpResponse.setHeader("Content-Security-Policy", 
                    "default-src 'self'; " +
                    "script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; " +
                    "style-src 'self' 'unsafe-inline' https:; " +
                    "img-src 'self' data: https:; " +
                    "font-src 'self' https:; " +
                    "connect-src 'self' https:; " +
                    "media-src 'self' https:; " +
                    "object-src 'none'; " +
                    "base-uri 'self';"
                );
                
                // Strict-Transport-Security: 强制HTTPS（仅在HTTPS环境下设置）
                if (request.getScheme().equals("https")) {
                    httpResponse.setHeader("Strict-Transport-Security", 
                        "max-age=31536000; includeSubDomains; preload");
                }
                
                // Cache-Control: 缓存控制，替代Expires头
                String requestURI = ((jakarta.servlet.http.HttpServletRequest) request).getRequestURI();
                if (requestURI.contains("/api/")) {
                    // API响应不缓存
                    httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                    httpResponse.setHeader("Pragma", "no-cache");
                    httpResponse.setHeader("Expires", "0");
                } else if (requestURI.contains("/assets/") || requestURI.contains("/images/")) {
                    // 静态资源长期缓存
                    httpResponse.setHeader("Cache-Control", "public, max-age=31536000, immutable");
                } else {
                    // 其他资源短期缓存
                    httpResponse.setHeader("Cache-Control", "public, max-age=3600");
                }
                
                // 隐藏服务器信息
                httpResponse.setHeader("Server", "WebServer");
                
                // Permissions-Policy: 权限策略
                httpResponse.setHeader("Permissions-Policy", 
                    "camera=(), microphone=(), geolocation=(), payment=()");
                
                chain.doFilter(request, response);
            }
        };
    }
}
